package in.muton.edushare.components.messaging.sendpanel;

import in.muton.edushare.components.messaging.api.UserMessage;
import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.wicket.converters.choicerenderers.PrivacyRenderer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.util.StringUtil;
import com.edushare.common.vo.EduShareEntity;
import com.edushare.common.vo.Messages;
import com.edushare.common.vo.Users;

public class MessagePanel extends EdusharePanel {

	private static final Log log = LogFactory.getLog(MessagePanel.class);

	public MessagePanel(String id, final IModel<? extends Object> model,
			EduShareBasePage page) {
		super(id, model, page);
		log.debug("Model = " + model.getObject());
		final PrivacyRenderer p = new PrivacyRenderer(model.getObject());
		Form<Void> f = new Form<Void>("form") {
			@Override
			public void onSubmit() {
				if (StringUtil.isValid(message)) {
					if (!UserMessage.isValidMessage(message)) {
						setError("Your message is too long and cannot be sent. Please try sending a shorter message.");
						return;
					}
					log.debug("Sending user message " + message);
					new UserMessage(message).setReciever(model.getObject())
							.setPrivacy(p.getoption()).send();
					message = "";
					if (p.getoption() != Messages.PRIVACY_TYPE_PUBLIC) {
						setError("Your message has been sent to a restricted audience.");
						return;
					}
				}else{
					setError("Cannot send empty messages.");
				}
			}

			private static final long serialVersionUID = -7726525096750720107L;
		};
		add(f);

		f.add(new Label("grpName", ((EduShareEntity) model.getObject())
				.getTitle()));
		WebMarkupContainer wmc;
		f.add(wmc = new WebMarkupContainer("privacyPanel"));
		if (model.getObject() instanceof Users) {
			wmc.setVisible(false);
		}
		wmc.add(new DropDownChoice<String>("privacy",
				new PropertyModel<String>(p, "privacyOption"), p.getOptions(),
				p));
		f.add(new TextArea<String>("message", new PropertyModel<String>(this,
				"message")));
		f.add(new Button("submit"));
	}

	private String message = "";

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	private static final long serialVersionUID = 1L;
}
